import requests
import base64
import json

from src.config import API_KEY, SECRET_KEY, APP_ID

def get_access_token():
    # 获取Access Token
    auth_url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        'grant_type': 'client_credentials',
        'client_id': API_KEY,
        'client_secret': SECRET_KEY
    }
    response = requests.post(auth_url, data=params)
    if response:
        return response.json().get('access_token')
    return None

def recognize_audio(audio_chunks):
    if not audio_chunks:
        print("没有音频数据")
        return None

    # 检查audio_chunks确保它是一个列表
    if not isinstance(audio_chunks, list):
        print("audio_chunks不是一个列表。")
        return None
    
    # 合并列表中的所有字节序列
    audio_data = b''.join(audio_chunks)
    access_token = get_access_token()
    if not access_token:
        return "无法获取Access Token"

    # 将音频数据转换为Base64编码
    audio_base64 = base64.b64encode(audio_data).decode('utf-8')

    # 设置API URL
    recognize_url = f"https://vop.baidu.com/server_api"

    # 构建请求参数
    data = {
        'format': 'wav',    # 根据实际音频格式调整
        'rate': 16000,      # 根据实际音频采样率调整
        'dev_pid': 1737,    # 根据需要选择语言和模型
        'channel': 1,       # 对于单声道音频设置为1
        'speech': audio_base64,
        'cuid': APP_ID,
        'token': access_token,
        'len': len(audio_data)
    }

    # 发送请求
    response = requests.post(recognize_url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

    if response:
        result_json = response.json()
        if 'result' in result_json:
            return '\n'.join(result_json['result'])
        else:
            return "识别失败：" + result_json.get('err_msg', '')
    return "API请求失败"

